package com.houger.ddd.seckill.infra.datamanager;

import com.houger.ddd.datamanager.entity.InventoryId;
import com.houger.ddd.datamanager.manager.aop.Inventory;
import com.houger.ddd.datamanager.operator.InventoryOperator;
import com.houger.ddd.datamanager.utils.OperatorResult;
import com.houger.ddd.seckill.constant.InvLimitTypeEnum;
import com.houger.ddd.seckill.infra.entity.ActivityRewardItem;
import com.houger.ddd.seckill.repository.ActivityRewardItemRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;


@Component
@Inventory("activity-item")
public class ActivityRewardItemInventoryOperator implements InventoryOperator {

    @Resource
    ActivityRewardItemRepository activityRewardItemRepository;

    public InventoryId getInventoryId(long initiatorRewardItemId){
        InventoryId id = new InventoryId(initiatorRewardItemId);
        return id;
    }

    @Override
    public long getTotal(InventoryId id) {
        final ActivityRewardItem item = this.activityRewardItemRepository.findById(id.getId()).orElseThrow();
        final Integer invLimitType = item.getInvLimitType();
        if(invLimitType.equals(InvLimitTypeEnum.NO_LIMIT.getValue())){
            return Long.MAX_VALUE;
        }
        return item.getInvTotal().longValue();
    }

    @Override
    public long getUsed(InventoryId id) {
        final ActivityRewardItem item = this.activityRewardItemRepository.findById(id.getId()).orElseThrow();
        return item.getInvUsed();
    }

    @Override
    public OperatorResult deduct(InventoryId id, long cnt) {
        return null;
    }

    @Override
    public OperatorResult release(InventoryId id, long cnt) {
        return null;
    }

    @Override
    public boolean flushUsed(InventoryId id, long cnt) {
        return this.activityRewardItemRepository.updateInvUsedById(id.getId(),cnt) == 1;
    }

}
